#define _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    int trap(vector<int>& height) {
        if (height.size() == 0) {
            return 0;
        }
        int n = height.size();
        int left = 0, right = n - 1;
        int max_left = height[0], max_right = height[n - 1];
        int ans = 0;
        while (left <= right) {
            max_left = max(max_left, height[left]);
            max_right = max(max_right, height[right]);
            if (max_left < max_right) {
                ans += max_left - height[left];
                left++;
            }
            else {
                ans += max_right - height[right];
                right--;
            }
        }
        return ans;
    }
};